package com.hyl.gulimall.member.config;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * @author hyl_marco
 * @data 2022/5/21 - 13:57
 */
@Configuration
public class GulimallFeignConfig {

    /**
     * fegin的拦截器定义
     * @return
     */
    @Bean("requestInterceptor")
    public RequestInterceptor requestInterceptor(){
        return  new RequestInterceptor() {
            @Override
            public void apply(RequestTemplate requestTemplate) {
                //1. RequestContextHolder拿到刚进来请求数据，强转为ServletRequestAttributes
                ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
                if(requestAttributes != null){
                    //2. 获得当前请求
                    HttpServletRequest request = requestAttributes.getRequest();
                    if(request != null){
                        //3. 同步请求头数据cookie放至feign要封装的新请求当中
                        //这里设置空判断的原因是，有请求才去设置请求
                        String cookie = request.getHeader("Cookie");
                        requestTemplate.header("Cookie",cookie);
                    }
                }

            }
        };
    }
}
